const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class TenantController extends Controller {
	/**
	 * 获取租户列表
	 */
	async list(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '该用户无权限'
				})
			}
			try{
				var tenant = await dbJQL.collection("mh-sys-tenant")
					.where(`_id != '0' && deleted != 1`)
					.get();
				if(tenant.data){
					return success({
						code: 0,
						data: tenant.data
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			controller,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'POST')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '该用户无权限'
				})
			}
			if(!ctx.data._id) return fail({
				code: 1,
				message: '参数缺失 [_id]'
			})
			try{
				// 创建租户
				var result = await dbJQL.collection("mh-sys-tenant").add(ctx.data);
				if(result.id) {
					//创建-根部门
					await dbJQL.collection("mh-sys-organization").add({
						isRoot: 1,
						dingtalkDepId: 1,//钉钉根部门id=1
						organizationName: ctx.data.tenantName,
						tenantId: result.id,
						createUserId: ctx.auth.loginUserId,
					});
					//初始化-内置字典（tenantId=1的字典）
					await controller.dict.initDict(result.id);
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '该用户无权限'
				})
			}
			try{
				var tenantId = ctx.data._id;
				if(!tenantId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				var result = await dbJQL.collection("mh-sys-tenant")
					.doc(tenantId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 删除（同时所有表该租户tenantId的数据deleted设为1，待定）
	 * @example ?_id=111111
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '该用户无权限'
				})
			}
			try{
				var tenantId = ctx.query._id;
				if(!tenantId) return fail({
					code: 1,
					message: '参数无效'
				})
				//删除
				var result = await dbJQL.collection("mh-sys-tenant")
					.doc(tenantId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 获取Super的菜单数据
	 */
	async superMenuList(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isSuperAdmin(ctx)){
				return fail({
					code: 1,
					message: '该用户无权限'
				})
			}
			try{
				var sort = 'sortNumber';
				var order = 'asc';
				var result = await dbJQL.collection("mh-sys-menu")
					.where(`tenantId == '0' && deleted != 1`)
					.orderBy(`${sort}`, `${order}`)
					.get()
				if(result.data){
					return success({
						code: 0,
						data: result.data
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	
	
	
}

